package gemini.castor.ui.client.page.widget.localebox;

import gemini.castor.ui.client.constants.I18nConstants;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.http.client.UrlBuilder;
import com.google.gwt.i18n.client.LocaleInfo;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Window.Location;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;

public class LocaleBoxWidget extends Composite {

	private HorizontalPanel pnlContainer;

	private I18nConstants constants;

	public LocaleBoxWidget() {
		constants = GWT.create(I18nConstants.class);
		initCustom();
		initWidget(pnlContainer);
	}

	private void initCustom() {
		// Add the option to change the locale
		final ListBox localeBox = new ListBox();
		String currentLocale = LocaleInfo.getCurrentLocale().getLocaleName();
		if (currentLocale.equals("default")) {
			currentLocale = "en_US";
		}
		String[] localeNames = LocaleInfo.getAvailableLocaleNames();
		for (String localeName : localeNames) {
			if (!localeName.equals("default")) {
				String nativeName = LocaleInfo
						.getLocaleNativeDisplayName(localeName);
				localeBox.addItem(nativeName, localeName);
				if (localeName.equals(currentLocale)) {
					localeBox.setSelectedIndex(localeBox.getItemCount() - 1);
				}
			}
		}

		localeBox.addChangeHandler(new ChangeHandler() {
			public void onChange(ChangeEvent event) {
				String localeName = localeBox.getValue(localeBox
						.getSelectedIndex());
				UrlBuilder builder = Location.createUrlBuilder().setParameter(
						"locale", localeName);
				Window.Location.replace(builder.buildString());
			}
		});

		pnlContainer = new HorizontalPanel();
		
		pnlContainer.setStyleName("widgetLocalePanel");
		HTML htmCaptionWidget = new HTML(constants.htmSelectLanguage());
		htmCaptionWidget.setStyleName("widgetLocaleCaption");
		pnlContainer.add(htmCaptionWidget);
		pnlContainer.add(localeBox);

	}
}
